import {ILoginInfo,ILoginByClassName} from "@/@types/main"
// 输入字符串，for循环 按序模拟键盘输入，默认已经focus 用 async await sleep方式写
const simulateKeyPress = async (element: HTMLInputElement, value: string) => {
  element.focus();
  element.value = "";
  for (let i = 0; i < value.length; i++) {
    await new Promise(resolve => setTimeout(resolve, 20));
    element.value += value[i];
    element.dispatchEvent(new Event("input", { bubbles: true }));
  }
};

// 获取 dom 通过 className
const getDomByClassName = (className: ILoginByClassName) => {
  const usernameInput = document.querySelector(className.username) as HTMLInputElement;
  const passwordInput = document.querySelector(className.password) as HTMLInputElement;
  const loginBtn = document.querySelector(className.loginBtn) as HTMLButtonElement;
  return { usernameInput, passwordInput, loginBtn };
};

// 通过 账号密码输入框和登录按钮登录

export const loginByCredentialsSimulate = async (info: ILoginInfo,className:ILoginByClassName) => {
  // 这里可以添加实际的登录逻辑，例如发送请求到后端
  const { usernameInput, passwordInput, loginBtn } = getDomByClassName(className);
  if (usernameInput && passwordInput && loginBtn) {
    await simulateKeyPress(usernameInput, info.pwd.name);
    await simulateKeyPress(passwordInput, info.pwd.pwd);
    setTimeout(()=>{
      loginBtn.click();
    },200)
  }
};
// 通过 账号密码输入框和登录按钮登录

export const loginByCredentials  = (info: ILoginInfo,className:ILoginByClassName) => {
  // 这里可以添加实际的登录逻辑，例如发送请求到后端
  const { usernameInput, passwordInput, loginBtn } = getDomByClassName(className);
  if (usernameInput && passwordInput && loginBtn) {
    usernameInput.focus();
    usernameInput.value = info.pwd.name;
    passwordInput.focus();
    passwordInput.value = info.pwd.pwd;
    setTimeout(()=>{
      loginBtn.click();
    },200)
    
  }
  console.log("login ok!")
};

